#ifndef _DVR_MML_SVR_H_
#define _DVR_MML_SVR_H_
#include "cross_com.h"
#include <thread>
#include <mutex>
#include <list>
using namespace std;

#ifdef _WIN32
#else
#include <errno.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <netinet/tcp.h>
#endif
enum {
	USERQUIT = -4,
	SOCKETSERVERCLOSE = -3,
	SOCKETTIMEOUT = -2,
	SOCKETERROR = -1,
	SOCKETNODATA = 0,
	SOCKETSUCCESS = 1,
};

typedef struct _STREAM_SVR_INFO_
{
	void *       pTask;
	int          clientID;	
	int          stream_ch;		 
	int          sock_idx;		 
	bool         bMix_ch;		 
	int          send_ch_bit;	  
	int          last_ch;
	bool          isReplay;
	int           replay_id;
	int          send_cnt;
	unsigned char * frmBuf;
#ifdef _WIN32
	SOCKET        clientSock;
#else
	int			  clientSock;
#endif
}STREAM_SVR_INFO_S, * PSTREAM_SVR_INFO_S;

class CStreamerSvr
{
public:

	CStreamerSvr();
	~CStreamerSvr();

	int Init(int send_buf_sz,int portNum,bool bSend = true);

	int Start();
	int Stop();

	int ListenProc();
	
	int StartStreamSvr(int clntSock,int index);

	int RcvData(char * buf ,int buf_sz,int conn_fd);

	int SendData(unsigned char* buf, int len, int flags,int conn_fd);

	int ReadFrameData(unsigned char * pFrm,int buf_sz,int ch,int clientID);

	STREAM_SVR_INFO_S*  GetFreeClientInfo(int sock,int index );

	void DestroyClient(int sock);

	int  GetDestMixCh();
	int get_client_id();

	void SwitchPlayMod(int replay_id ,bool bReplay)
	{
		for(int i = 0; i < 4;i++)
		{
			if(replay_id == m_stream_client[i].replay_id)
			{	
				m_stream_client[i].isReplay = bReplay;
				m_stream_client[i].send_cnt = 0;
				printf("SwitchPlayMod replay_id %d bReplay %d .\n",replay_id,bReplay);
				break;
			}
		}
	}

	void stop_stream()
	{
		m_stop_stream = true;
	}
	int GetSocket()
	{
		return (int)m_sock;
	}

	void SetLiveCH(int chBit)
	{
		LIVE_SEND_BIT = chBit;
	}
	static int PUB_THREAD_CALL StreamProc(void * pParam);
	static int PUB_THREAD_CALL StreamHeartProc(void * pParam);
	static int PUB_THREAD_CALL StreamProcRecv(void * pParam);
    int LIVE_SEND_BIT;
protected:
	unsigned char * m_rcvBuf;
	int             m_rcvBuf_sz;
	//���ͳ�ȥ��BUF
	char *			m_sendBuf;
	int             m_send_sz;
	struct sockaddr_in m_servaddr;
	int           m_live_ch;
	int			  m_sockNum;
	bool          m_bStream_Live;
	fd_set		  m_fds;
	bool          m_bReplay; 
	bool          m_bMix_ch;
	bool 		  m_stop_stream = false;
	std::thread   m_thd;
	std::thread   m_thd_svr; 
#ifdef _WIN32
	SOCKET           m_sock;
	SOCKET           m_send_sock[1024];
#else
	int				 m_sock;
	int			    m_send_sock[1024];
#endif
	STREAM_SVR_INFO_S m_stream_client[4];
	bool               m_bSendSvr;
	std::mutex      m_lock;
	bool  m_bThdLive;
	//list<> m_lst_; 
};

#define SOCK_SIZE 1024
#endif //_DVR_CMD_APP_H_
